/*******************************************************************************
 * Copyright (c) 2011 Prometheus Consulting
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
/**
 * 
 */
package nz.co.senanque.vaadinsupport.I18n;

import java.lang.reflect.Field;
import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.StringUtils;

import com.vaadin.ui.AbstractField;
import com.vaadin.ui.Component;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.Label;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TabSheet.Tab;

/**
 * Scan the object passed and translate each caption and label value according to the current locale.
 * It uses the Spring MessageSourceAccessor to manage the translation.
 * Note that you don't need this when using Madura Objects, but if you have a form that isn't bound to
 * a Madura Object you can run this against it to translate all the captions.
 * 
 * @author Roger Parkinson
 *
 */
public class I18nCaptionHelper {
	
	private static Logger logger = LoggerFactory.getLogger(I18nCaptionHelper.class);
	
//	public static void setCaptions(Object layout, MessageSourceAccessor messageSourceAccessor)
//	{
//		Field[] fields = layout.getClass().getDeclaredFields();
//		for (Field field: fields)
//		{
//			field.setAccessible(true);
//			Object fieldValue=null;
//			try {
//				fieldValue = field.get(layout);
//			} catch (Exception e) {
//				logger.warn("Error getting field",e);
//				continue;
//			}
//			if (fieldValue instanceof AbstractField)
//			{
//				AbstractField abstractField = (AbstractField)fieldValue;
//				String caption = abstractField.getCaption();
//				if (StringUtils.hasLength(caption))
//				{
//					caption = messageSourceAccessor.getMessage(caption, null,caption);
//					if (caption.indexOf('}') == -1)
//					{
//						abstractField.setCaption(caption);
//					}
//				}
//			}
//			else if (fieldValue instanceof Label)
//			{
//				com.vaadin.ui.Label label = (com.vaadin.ui.Label)fieldValue;
//				Object caption = label.getValue();
//				if (caption instanceof String && StringUtils.hasLength((String)caption))
//				{
//					String captionString = messageSourceAccessor.getMessage((String)caption, null,(String)caption);
//					if (captionString.indexOf('}') == -1)
//					{
//						label.setValue(captionString);
//					}
//				}
//			}
//			else if (fieldValue instanceof TabSheet)
//			{
//				TabSheet tabsheet = (TabSheet)fieldValue;
//				int j=0;
//		        for (final Iterator<Component> i = tabsheet.getComponentIterator(); i.hasNext();) {
//		            final Component component = i.next();
//		            Tab tab = tabsheet.getTab(j++);
//	            	String caption = tab.getCaption();
//					caption = messageSourceAccessor.getMessage((String)caption, null,(String)caption);
//					tab.setCaption(caption);
//		        }
//			}
//		}
//	}

	public static String[] getColumnHeaders(String[] englishColOrder,
			MessageSourceAccessor messageSourceAccessor) {
		int size = englishColOrder.length;
		String[] ret = new String[size];
		for (int i=0;i<size;i++)
		{
			ret[i] = messageSourceAccessor.getMessage(englishColOrder[i], null,englishColOrder[i]);
		}
		return ret;
	}
	public static void switchCaptions(Component component, MessageSourceAccessor messageSourceAccessor) {
		if (component instanceof AbstractField)
		{
			switchCaption((AbstractField)component,messageSourceAccessor);
		}
		if (component instanceof Label)
		{
			switchCaption((Label)component,messageSourceAccessor);
		}
		if (component instanceof ComponentContainer)
		{
			switchCaption((ComponentContainer)component,messageSourceAccessor);
		}
		if (component instanceof TabSheet)
		{
			switchCaption((TabSheet)component,messageSourceAccessor);
		}
	}
	private static void switchCaption(ComponentContainer componentContainer, MessageSourceAccessor messageSourceAccessor)
	{
		String newCaption = getTranslatedCaption(componentContainer.getCaption(),messageSourceAccessor);
		if (newCaption != null)
		{
			componentContainer.setCaption(newCaption);
		}
		Iterator<Component> it = componentContainer.getComponentIterator();
		while (it.hasNext())
		{
			Component subcomponent = it.next();
			switchCaptions(subcomponent,messageSourceAccessor);
		}
	}
	private static void switchCaption(AbstractField field, MessageSourceAccessor messageSourceAccessor)
	{
		String newCaption = getTranslatedCaption(field.getCaption(),messageSourceAccessor);
		if (newCaption != null)
		{
			field.setCaption(newCaption);
		}
	}
	private static void switchCaption(TabSheet tabSheet, MessageSourceAccessor messageSourceAccessor)
	{
		int j=0;
        for (final Iterator<Component> i = tabSheet.getComponentIterator(); i.hasNext();) {
            final Component component = i.next();
            Tab tab = tabSheet.getTab(j++);
    		String newCaption = getTranslatedCaption(tab.getCaption(),messageSourceAccessor);
    		if (newCaption != null)
    		{
    			tab.setCaption(newCaption);
    		}
        }
	}
	private static void switchCaption(Label label, MessageSourceAccessor messageSourceAccessor)
	{
		String newCaption = getTranslatedCaption((String)label.getValue(),messageSourceAccessor);
		if (newCaption != null)
		{
			label.setValue(newCaption);
		}
	}
	public static String getTranslatedCaption(String caption, MessageSourceAccessor messageSourceAccessor)
	{
		if (caption == null)
		{
			return null;
		}
		if (caption.indexOf('}') == -1)
		{
			String newCaption = messageSourceAccessor.getMessage(caption,null,caption);
			if (newCaption.indexOf('}') == -1)
			{
				return newCaption;
			}
		}
		return null;
		
	}

}
